<template>
  <selected-form-item>
    <selected-box :value.sync="value" :disabled="disabled" @change="handleChange" />
    <slot :disabled="disabled" :multiple="multiple" :confirm="handleChange" />
  </selected-form-item>
</template>

<script>
import { isArray, SelectedFormItem, SelectedBox, isEmptyObject } from "@monkey.do/monkey";

export default {
  name: "CustomerChoose",

  components: {
    SelectedFormItem,
    SelectedBox,
  },

  props: {
    data: {
      type: null,
      default: () => ({}),
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      value: [],
    };
  },

  watch: {
    data: {
      handler: function(value) {
        this.updateData(value);
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    updateData(value) {
      if (!value) {
        this.value = [];
        return;
      }
      if (isArray(value)) {
        this.value.splice(0, this.value.length, ...value);
      } else {
        if (value && !isEmptyObject(value)) {
          this.value.splice(0, this.value.length, value);
        } else {
          this.value.splice(0, this.value.length);
        }
      }
    },

    handleChange(value) {
      if (this.multiple) {
        this.$emit("change", value);
        this.$emit("update:value", value);
      } else {
        this.$emit("change", value[0] || {});
        this.$emit("update:value", value[0] || {});
      }
      this.updateData(value);
    },
  },
};
</script>
